package cn.org.xuanzp.nty.client.handler;

import cn.hutool.json.JSONUtil;
import cn.org.xuanzp.nty.client.Client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * @Classname NettyClientHandler
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/9/24 23:02
 * @Created by xuanzp
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter { // (1)

    private Client client;

    public NettyClientHandler(Client client) {
        this.client = client;
    }

    // 每次有数据的时候会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        System.out.println("NettyClientHandler:调用当前的channelRead方法！");

        try {
            System.out.println("开始读取服务器发送的数据！,"+ JSONUtil.toJsonStr(msg));

        } catch (Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg);// (3)这里必须要释放
        }
    }

    // 第一次连接上服务器的时候被调用
    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        System.out.println("NettyClientHandler:调用当前的channelActive方法！,channel().id="+ctx.channel().id().asLongText());
        client.open(ctx);
    }

    // 出现异常的时候，直接关闭这个连接
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        System.out.println("NettyClientHandler:调用当前的exceptionCaught方法！");
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
        client.removeCtx();
    }

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }
}

